package cn.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import cn.pojo.Detail;
import cn.pojo.Sort;
import cn.service.DetailService;
import cn.service.SortService;
import cn.util.DateUtil;
import cn.util.Page;

@Controller
@RequestMapping("/detail")
public class DetailController {
	@Resource
	private DetailService detailService;
	@Resource
	private SortService sortService;

	@RequestMapping("/getDetail")
	private String getDetail(@RequestParam(value = "sortId", defaultValue = "0", required = false) Long sortId, //
			@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum, //
			HttpServletRequest request, HttpServletResponse response, Model md) {
		Page<Detail> page = new Page<Detail>();
		page.init(detailService.totalCount(sortId), pageNum);
		List<Detail> list = detailService.getDetails(sortId, page.getRowNum(), Page.pageCount);
		for (int i = 0; i < list.size(); i++) {
			list.get(i).setSort(sortService.getSortById(list.get(i).getSortId()));
			list.get(i).setCreateDate(DateUtil.convertUtilDateToTimeStamp(list.get(i).getCreateDate()));
		}
		page.setList(list);
		// System.out.println(list);
		md.addAttribute("PAGE", page);
		md.addAttribute("SORTID",sortId);
		return "goodsList";
	}

	@RequestMapping("/toShopping")
	private String toShopping(@RequestParam(value = "id", defaultValue = "0", required = false) Long id, //
			@RequestParam(value = "sortId", defaultValue = "0", required = false) Long sortId, //
			HttpServletRequest request, HttpServletResponse response, Model md) {
		Detail de = detailService.getDetailById(id);
		Sort sort = sortService.getSortById(sortId);
		md.addAttribute("DETAIL", de);
		md.addAttribute("SORT", sort);
		return "shopping";
	}

	@RequestMapping("/updateDetail")
	public String updateDetail(@RequestParam(value = "shopNum", defaultValue = "0", required = false) Integer shopNum, //
			@RequestParam(value = "id", defaultValue = "0", required = false) Long id,
			@RequestParam(value = "remaining", defaultValue = "0", required = false) Integer remaining) {
		int i = detailService.updateDetail(remaining - shopNum, id);
		return "redirect:/detail/getDetail";
	}
}
